from django.http import HttpResponse, Http404, HttpRequest
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from studenthoods.apps.facebook.models import FacebookCompetition, Entrant
from time import strftime

from studenthoods.apps.facebook.forms import EntryForm
from studenthoods.apps.facebook.utils import like_us

from datetime import date


@csrf_exempt
def competition(request, app_id):

    try:
        competition = FacebookCompetition.objects.get(app_id=app_id)
    except FacebookCompetition.DoesNotExist:
        raise Http404

    signed_request = request.REQUEST.get('signed_request', None)

    if date.today() > competition.closing_date:
        return render_to_response('facebook/templates/closed.html', {
            'competition': competition,
        }, context_instance=RequestContext(request))
    elif signed_request is not None and not like_us(signed_request, competition.app_secret):
        return render_to_response('facebook/templates/likegate.html', {
            'competition': competition,
        }, context_instance=RequestContext(request))
    else:
        if request.method == 'POST' and request.POST.has_key('email'):

            form = EntryForm(request.POST)
            if form.is_valid():
                
                entrant = Entrant()
                entrant.name = form.cleaned_data['name']
                entrant.email = form.cleaned_data['email']
                entrant.size = form.cleaned_data['size']
                entrant.university = competition.university
                entrant.competition = competition
                entrant.save()

                return render_to_response('facebook/templates/entry_thanks.html', {
                    'competition': competition,
                }, context_instance=RequestContext(request))

        else:
            form = EntryForm()
        
        return render_to_response('facebook/templates/entry.html', {
            'form':form,
            'competition': competition,
        }, context_instance=RequestContext(request))